<?php defined('BASEPATH') or exit('No direct script access allowed');


/** PHPLinq_LinqToObjects */

class Channel_Result_m extends L_Model
{
	public function __construct(){
		parent::__construct();
		$this->set_table_name("channel_result");
	}

	public function getByDateRange($channel_id, $fromdate, $todate){
		$sql = "SELECT * FROM `l_channel_result` WHERE channel_id = ? AND date(open_date) >= ? AND date(open_date) <= ? ORDER BY open_date DESC, prize ASC";

		$dataList = $this->db->query($sql, array($channel_id, $fromdate, $todate))->result();

		$dateList =array();
		$detailList = array();
		$open_date='';
		foreach($dataList as $d){
			$open_date = $d->open_date;
			if(!in_array($open_date,$dateList)){
				$dateList[]=$open_date;
				$detailList[$open_date]=array();
			}

			$detailList[$open_date][]=$d;
		}

		return array('dateList'=>$dateList,'detailList'=>$detailList);
	}


	public function tryGetByDate($channel_id, $open_date){
		$sql = "SELECT * FROM `l_channel_result` WHERE channel_id = ? AND date(`open_date`) = ? ORDER BY prize";

		$result = $this->db->query($sql, array($channel_id, $open_date))->result();

		if(sizeof($result)==0)
		{
			$sql='SELECT l1.* FROM `l_channel_result` l1 '
			.' INNER JOIN (SELECT MAX(open_date) AS open_date FROM `l_channel_result` WHERE channel_id = ? ) l2 '
			.' ON l1.open_date=l2.open_date'
			.' WHERE l1.channel_id = ?'
			.' ORDER BY l1.prize';

			$result = $this->db->query($sql, array($channel_id,$channel_id))->result();
				
			foreach($result as $r){
				$r->result='Please enter';
			}
		}

		return $result;
	}

	public function insertOrUpdateResult($channel_id, $open_date, $prizeList){

		// Delete first
		$sqlDelete ="DELETE FROM `l_channel_result` WHERE channel_id = ? AND date(open_date) = ? ";
		$this->db->query($sqlDelete, array($channel_id, $open_date));

		// Insert
		$counter=0;
		foreach($prizeList as $prize){
			foreach($prize as $p){
				$data=array(
					'channel_id'=>$channel_id,
					'open_date' =>$open_date,
					'prize'=>$counter,
					'result'=>$p
				);
				
				$this->insert($data, true);
			}
			$counter++;			
		}
	}

}